<template>
  <el-dialog v-model="visible" title="床位调换" width="40%" :close-on-click-modal="false" class="exchange-bed-dialog" draggable>
    <el-form :model="form" label-width="100px" style="width:100%;">
      <el-form-item label="客户姓名">
        <el-input v-model="form.clientName" disabled style="width:100%;" />
      </el-form-item>
      <el-form-item label="原床位">
        <el-input :value="`${form.building}栋${form.floor}层${form.roomNo}房${form.bedNo}号`" disabled style="width:100%;" />
      </el-form-item>
      <el-form-item label="新房间">
        <el-cascader v-model="form.newRoomCascader" :options="roomCascaderOptions" placeholder="请选择新房间"
          style="width:100%;" :props="roomCascaderProps" clearable @change="onRoomCascaderChange" />
      </el-form-item>
      <el-form-item label="床位号">
        <el-select v-model="form.newBedId" :disabled="!bedOptions.length" filterable placeholder="请选择床位号"
          style="width:100%;">
          <el-option v-for="bed in bedOptions" :key="bed.bedId" :label="`${bed.bedNumber}号`" :value="bed.bedId" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false" style="width:38%;">取消</el-button>
        <el-button type="primary" @click="onSubmit" style="width:38%;margin-left:6%;">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineExpose, defineEmits } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import qs from 'qs'

const visible = ref(false)
const form = ref({
  usageId: '',
  clientId: '',
  clientName: '',
  building: '',
  floor: '',
  roomNo: '',
  bedNo: '',
  newRoomCascader: [], // [building, floor, roomNo]
  newBedId: ''         // 单独床位id
})
const allFreeBeds = ref([]) // 后端所有空闲床位平铺数组
const roomCascaderOptions = ref([])
const bedOptions = ref([])
const emit = defineEmits(['refresh'])

const roomCascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children',
  checkStrictly: false,
  emitPath: true
}

const open = async (row) => {
  form.value.usageId = row.bedUsage.usageId
  form.value.clientId = row.client.clientId
  form.value.clientName = row.client.name
  form.value.building = row.bedUsage.building || ''
  form.value.floor = row.bedUsage.floor || ''
  form.value.roomNo = row.bedUsage.roomNo || ''
  form.value.bedNo = row.bedUsage.bedNo || ''
  form.value.newRoomCascader = []
  form.value.newBedId = ''
  bedOptions.value = []

  // 获取空闲床位
  try {
    const { data } = await axios.get('http://localhost:9000/bed/getFreeNum')
    if (data.status === 200 && data.data) {
      // 展平成数组
      allFreeBeds.value = Object.values(data.data).flat()
      // 构建级联结构
      roomCascaderOptions.value = buildRoomCascader(allFreeBeds.value)
    } else {
      roomCascaderOptions.value = []
      allFreeBeds.value = []
      ElMessage.error(data.msg || '空闲床位查询失败')
    }
  } catch {
    roomCascaderOptions.value = []
    allFreeBeds.value = []
    ElMessage.error('空闲床位查询失败')
  }
  visible.value = true
}

// 辅助函数：构建楼栋-楼层-房间号级联结构
function buildRoomCascader(beds) {
  const result = []
  beds.forEach(item => {
    let buildingNode = result.find(x => x.value === item.building)
    if (!buildingNode) {
      buildingNode = { value: item.building, label: item.building, children: [] }
      result.push(buildingNode)
    }
    let floorNode = buildingNode.children.find(x => x.value === item.floorNumber)
    if (!floorNode) {
      floorNode = { value: item.floorNumber, label: item.floorNumber, children: [] }
      buildingNode.children.push(floorNode)
    }
    let roomNode = floorNode.children.find(x => x.value === item.roomNumber)
    if (!roomNode) {
      roomNode = { value: item.roomNumber, label: item.roomNumber + '房' }
      floorNode.children.push(roomNode)
    }
  })
  return result
}

// 当房间选择变更时，更新床位选项
function onRoomCascaderChange(val) {
  if (val.length !== 3) {
    bedOptions.value = []
    form.value.newBedId = ''
    return
  }
  const [building, floorNumber, roomNumber] = val
  bedOptions.value = allFreeBeds.value.filter(b =>
    b.building === building &&
    b.floorNumber === floorNumber &&
    b.roomNumber === roomNumber
  )
  form.value.newBedId = ''
}

const onSubmit = async () => {
  if (!form.value.newRoomCascader.length || !form.value.newBedId) {
    ElMessage.warning('请选择完整的新房间和床位号')
    return
  }
  try {
    const { data } = await axios.post('http://localhost:9000/bedUsage/exchange', qs.stringify({
      usageId: form.value.usageId,
      bedId: form.value.newBedId
    }))
    if (data.status === 200) {
      ElMessage.success('调换成功')
      visible.value = false
      emit('refresh')
    } else {
      ElMessage.error(data.msg || '调换失败')
    }
  } catch {
    ElMessage.error('请求失败')
  }
}

defineExpose({ open })
</script>

<style scoped>
.exchange-bed-dialog .dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 6%;
}
</style>
